using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.UI;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SOEI.Solution.Customized;
using SOEI.Solution.Customized.Dtos;
using SOEI.Solution.DomainEntities.Parameters.DomainService;
using SOEI.Solution.DomainEntities.Parameters.Dtos;
using SOEI.Solution.DomainEntities.PurQualificationAudit.DomainService;
using SOEI.Solution.DomainEntities.PurQualificationAudit.Dtos;
using SOEI.Solution.StructEntities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace SOEI.Solution.DomainEntities.PurQualificationAudit
{
    /// <summary>
    /// 【扩展模块】  <br/>
    /// 【功能描述】  ：XXX 模块<br/>
    /// 【创建日期】  ：2020.05.21 <br/>
    /// 【开发人员】  ：static残影<br/>
    ///</summary>
    [ApiExplorerSettings(GroupName = "Manager", IgnoreApi = false)]
    public class PurQualificationApplyAppService : SolutionAppServiceBase, IPurQualificationApplyAppService
    {
        /// <summary>
        ///【PurQualificationApply】仓储层
        /// </summary>
        private readonly IRepository<PurQualificationApply, string> _purqualificationapplyRepository;

        /// <summary>
        /// 购资审核申请变更表仓储
        /// </summary>
        private readonly IRepository<PurQualificationChage, string> _purQualificationChageRepository;

        private readonly IRepository<PurFamilyMember, string> _purFamilyMembersRepository;

        /// <summary> 
        /// 家庭成员变更表仓储
        /// </summary>
        private readonly IRepository<PurFamilyMemberChange, string> _purFamilyMemberChangesRepository;

        /// <summary>
        ///【PurQualificationApply】领域服务
        /// </summary>
        private readonly IPurQualificationApplyManager _purqualificationapplyManager;

        /// <summary>
        /// 【Parameter】参数的领域服务
        /// </summary>
        private readonly IParameterManager _parameterManager;

        /// <summary>
        /// 【PurFamilyMember】家庭成员信息表的领域服务
        /// </summary>
        private readonly IPurFamilyMemberManager _purFamilyMemberManager;

        public PurQualificationApplyAppService(
            IRepository<PurQualificationApply, string> purqualificationapplyRepository,
            IPurQualificationApplyManager purqualificationapplyManager,
            IParameterManager parameterManager,
            IRepository<PurFamilyMember, string> purFamilyMembersRepository,
            IPurFamilyMemberManager purFamilyMemberManager,
            IRepository<PurQualificationChage, string> purQualificationChageRepository,
            IRepository<PurFamilyMemberChange, string> purFamilyMemberChangesRepository

        )
        {
            _purqualificationapplyRepository = purqualificationapplyRepository;
            _purqualificationapplyManager = purqualificationapplyManager;
            _parameterManager = parameterManager;
            _purFamilyMembersRepository = purFamilyMembersRepository;
            _purFamilyMemberManager = purFamilyMemberManager;
            _purQualificationChageRepository = purQualificationChageRepository;
            _purFamilyMemberChangesRepository = purFamilyMemberChangesRepository;
        }

        #region -------------------------------------------------辅助工具生成---------------------------------------------- 

        /// <summary>
        ///【PurQualificationApply】获取的分页列表信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task<PagedResultDto<PurQualificationApplyListDto>> GetPaged(GetPurQualificationApplysInput input)
        {
            //1. 获取当前登录的用户信息（）
            //2. 判断当前登录 是否经济机构用户
            await GetPersonChecker();

            var query = _purqualificationapplyRepository.GetAll()
                          //模糊搜索 字段Id
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.Id.Contains(input.FilterText));
            // TODO:根据传入的参数添加过滤条件

            var count = await query.CountAsync();

            var entityList = await query
                    .OrderBy(input.Sorting).AsNoTracking()
                    .PageBy(input)
                    .ToListAsync();

            var entityListDtos = ObjectMapper.Map<List<PurQualificationApplyListDto>>(entityList);
            return new PagedResultDto<PurQualificationApplyListDto>(count, entityListDtos);
        }

        /// <summary>
        ///【PurQualificationApply】通过指定id获取MemberListDto信息
        /// </summary>
        [AbpAuthorize()]
        public async Task<PurQualificationApplyListDto> GetById(EntityDto<string> input)
        {
            var entity = await _purqualificationapplyRepository.GetAsync(input.Id);

            var dto = ObjectMapper.Map<PurQualificationApplyListDto>(entity);
            return dto;
        }

        /// <summary>
        ///【Company】 获取编辑
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task<GetPurQualificationApplyForEditOutput> GetForEdit(EntityDto<string> input)
        {
            var output = new GetPurQualificationApplyForEditOutput();
            PurQualificationApplyEditDto editDto;

            if (!string.IsNullOrEmpty(input.Id))
            {
                var entity = await _purqualificationapplyRepository.GetAsync(input.Id);
                editDto = ObjectMapper.Map<PurQualificationApplyEditDto>(entity);
            }
            else
            {
                editDto = new PurQualificationApplyEditDto();
            }
            output.PurQualificationApply = editDto;
            return output;
        }
        /// <summary>
        ///【PurQualificationApply】 添加或者修改的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task CreateOrUpdate(CreateOrUpdatePurQualificationApplyInput input)
        {
            if (!string.IsNullOrEmpty(input.PurQualificationApply.Id))
            {
                await Update(input.PurQualificationApply);
            }
            else
            {
                await Create(input.PurQualificationApply);
            }
        }
        /// <summary>
        ///【PurQualificationApply】新增
        /// </summary>
        [AbpAuthorize()]
        protected virtual async Task<PurQualificationApplyEditDto> Create(PurQualificationApplyEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = ObjectMapper.Map<PurQualificationApply>(input);
            //调用领域服务
            entity = await _purqualificationapplyManager.CreateAsync(entity);

            var dto = ObjectMapper.Map<PurQualificationApplyEditDto>(entity);
            return dto;
        }

        /// <summary>
        ///【PurQualificationApply】编辑
        /// </summary>
        [AbpAuthorize()]
        protected virtual async Task Update(PurQualificationApplyEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新
            var key = input.Id;
            var entity = await _purqualificationapplyRepository.GetAsync(key);
            //  input.MapTo(entity);
            //将input属性的值赋值到entity中
            ObjectMapper.Map(input, entity);
            await _purqualificationapplyManager.UpdateAsync(entity);
        }

        /// <summary>
        ///【PurQualificationApply】删除信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task Delete(EntityDto<string> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _purqualificationapplyManager.DeleteAsync(input.Id);
        }

        /// <summary>
        ///【PurQualificationApply】 批量删除Member的方法
        /// </summary>
        [AbpAuthorize()]
        public async Task BatchDelete(List<string> input)
        {
            // TODO:批量删除前的逻辑判断，是否允许删除
            await _purqualificationapplyManager.BatchDelete(input);
        }

        #endregion

        #region -------------------------------------------------用户自定义------------------------------------------------
        /*请在此扩展应用服务实现*/

        /// <summary>
        ///【PurQualificationApply】 获取购资审核初始信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task<GetPurQualificationApplyForEditOutput> GetPurAuditInfo(EntityDto<string> input)
        {
            //1. 获取当前登录的用户信息（）
            //2. 判断当前登录 是否经济机构用户
            await GetPersonChecker();
            var output = new GetPurQualificationApplyForEditOutput();
            PurQualificationApplyEditDto editDto;

            //编辑时候选择下拉框-->证件类型
            var queryCertificateType = this._parameterManager.QueryCertificateType();
            var CertificateList = await queryCertificateType
                .AsNoTracking()
                .ToListAsync();
            output.CertificateTypes = ObjectMapper.Map<ICollection<ParameterListDto>>(CertificateList);


            //编辑时候选择下拉框-->买受人购房情况类型
            var queryBuyerConditionType = this._parameterManager.QueryBuyerConditionType();
            var BuyerConditionList = await queryBuyerConditionType.AsNoTracking().ToListAsync();
            output.BuyQualificationTypes = ObjectMapper.Map<ICollection<ParameterListDto>>(BuyerConditionList);

            //编辑时候选择下拉框-->户籍所在类型
            var queryCensusRegisterType = this._parameterManager.QueryCensusRegisterType();
            var CensusRegisterList = await queryCensusRegisterType.AsNoTracking().ToListAsync();
            output.CensusRegisterTypes = ObjectMapper.Map<ICollection<ParameterListDto>>(CensusRegisterList);

            if (!string.IsNullOrEmpty(input.Id))
            {
                var entity = await _purqualificationapplyRepository.GetAsync(input.Id);
                editDto = ObjectMapper.Map<PurQualificationApplyEditDto>(entity);
            }
            else
            {
                editDto = new PurQualificationApplyEditDto();
            }
            output.PurQualificationApply = editDto;
            return output;
        }

        /// <summary>
        /// 【PurQualificationApply】第一步--新增购审验证
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<SmsVerifyEditDto> SmsVerifySave(CreatOrUpdateSmsVerifyInput input)
        {
            //1. 获取当前登录的用户信息（）
            //2. 判断当前登录 是否经济机构用户
            await GetPersonChecker();
            //TODO:更新前的逻辑判断，是否允许更新

            //逻辑：判断是否当前机构
            if (string.IsNullOrEmpty(input.SmsVerify.DXYZSHHM))
            {
                throw new UserFriendlyException("买受人手机号码不可为空!");
            }
            //验证手机号码格式
            //CheckPhone(input.SmsVerify.LXDH);
            var Res = await GetCurrentUserAsync();
            PurQualificationApply purQualificationApply;
            purQualificationApply = ObjectMapper.Map<PurQualificationApply>(input.SmsVerify);

            //获取新的序列号
            purQualificationApply.Id = _purqualificationapplyManager.GetNewSequenceCode();
            //购房人人员类型为个人
            purQualificationApply.GFRLXDM = "01";
            //数据来源于新模式--与旧系统做区分
            purQualificationApply.SJLY = "XMS";
            //业务类型代码为JJD
            purQualificationApply.YWLXDM = "JJD";
            //申请状态代码为01--未提交
            purQualificationApply.SQZTDM = "01";
            //录入人编号
            purQualificationApply.LRRBH = Res.UserName;
            //录入人姓名
            purQualificationApply.LRRXM = Res.Name;
            //录入时间
            purQualificationApply.LRSJ = System.DateTime.Now;

            //调用领域服务
            var entity = await _purqualificationapplyManager.CreateAsync(purQualificationApply);

            return ObjectMapper.Map<SmsVerifyEditDto>(entity);

        }

        /// <summary>
        /// 【PurQualificationApply】第二部--证照上传
        /// </summary>
        /// <returns></returns>
        public async Task<PurQualificationApplyEditDto> TrailingUpdate(CreatOrUpdateTrailingUpdate input)
        {
            //1. 获取当前登录的用户信息（）
            //2. 判断当前登录 是否经济机构用户
            await GetPersonChecker();
            //校验
            await Verify(input);

            //购资审核申请信息保存
            var key = input.TrailingData.Id;
            var purentity = await _purqualificationapplyRepository.GetAsync(key);
            purentity.LXDH = null;
            purentity.GFRXM = null;
            purentity.ZJMC = null;
            purentity.ZJHM = null;

            input.TrailingData.purPeoInfors.ForEach((p) =>
            {
                input.purFamilyMemberData.purFamilyInfos.ForEach((q) =>
                {
                    if (p.GFRXM == q.XM && q.SFGFRDM == "01")
                    {
                        p.LXDH = q.LXDH;
                    }
                });
            });

            //购房人家庭成员中只要有一个本市则为本市：1本市；0：非本市
            for (var i = 0; i < input.purFamilyMemberData.purFamilyInfos.Count; i++)
            {
                if (input.purFamilyMemberData.purFamilyInfos[i].HKLXDM == "01")
                {
                    purentity.ISBS = "1";
                    break;
                }
                else
                {
                    purentity.ISBS = "0";
                    continue;
                }
            }

            foreach (var item in input.TrailingData.purPeoInfors)
            {
                //证件类型汉化
                item.ZJMC = ((CertificateType)Enum.Parse(typeof(CertificateType), item.ZJMC)).ToString();
                purentity.GFRXM += item.GFRXM + ",";  //购房人姓名
                purentity.ZJMC += item.ZJMC + ",";    //证件类型
                purentity.ZJHM += item.ZJHM + ",";    //证件名称
                purentity.LXDH += item.LXDH + ",";    //联系电话
            }
            purentity.GFRXM = purentity.GFRXM.Substring(0, purentity.GFRXM.LastIndexOf(","));
            purentity.ZJMC = purentity.ZJMC.Substring(0, purentity.ZJMC.LastIndexOf(","));
            purentity.ZJHM = purentity.ZJHM.Substring(0, purentity.ZJHM.LastIndexOf(","));
            purentity.LXDH = purentity.LXDH.Substring(0, purentity.LXDH.LastIndexOf(","));

            //获取限购类型代码
            var datetime = System.DateTime.Now; //获取当前系统时间
            var XGSJtime = "2017-01-01 00:00:00";
            purentity.ZLSCZTDM = "00";  //资料审查方式默认为00

            //将日期字符串转换为日期对象
            System.DateTime t1 = System.Convert.ToDateTime(datetime);
            System.DateTime t2 = System.Convert.ToDateTime(XGSJtime);
            int compNum = System.DateTime.Compare(t1, t2);
            if (compNum > 0)
            {
                purentity.XGLX = "1";  //如果当前时间大于XGSJtime，限购类型为1：2017年限购类型
            }


            var result = await _purqualificationapplyManager.MyUpdateAsync(purentity);
            var dto = ObjectMapper.Map<PurQualificationApplyEditDto>(result);


            //家庭成员信息保存
            List<JTCYXXID> JTCYXXIDS = new List<JTCYXXID>();
            foreach (var item in input.purFamilyMemberData.purFamilyInfos)
            {
                var GFZGSCSQBH = "";
                if (!string.IsNullOrEmpty(item.Id))
                {
                    var Purresult = await _purFamilyMemberManager.IsExistAsync(item.Id);
                    if (Purresult)
                    {
                        var prrentity = ObjectMapper.Map<PurFamilyMember>(item);
                        await _purFamilyMembersRepository.UpdateAsync(prrentity);
                    }
                }
                else
                {
                    //申请表主键id指向家庭成员信息表中的GFZGSCSQBH
                    item.GFZGSCSQBH = input.TrailingData.Id;
                    //数据来源于新模式
                    item.SJLY = "XMS";
                    //获取新的序列号
                    item.Id = _purqualificationapplyManager.GetSonNewSequenceCode();
                    var entity = ObjectMapper.Map<PurFamilyMember>(item);
                    entity = await _purFamilyMembersRepository.InsertAsync(entity);
                    GFZGSCSQBH = entity.Id;
                    JTCYXXIDS.Add(new JTCYXXID() { Id = entity.Id });
                    dto.JTCYXXIDS = JTCYXXIDS;
                }

                //家庭成员变更信息表保存
                //获取序列、变更人编号、变更时间-->当前系统时间
                var Res = await GetCurrentUserAsync();
                var ResultJTCYBG = ObjectMapper.Map<PurFamilyMemberChange>(item);
                ResultJTCYBG.Id = _purqualificationapplyManager.GetJTChangeSequence();
                ResultJTCYBG.BGRBH = Res.Id.ToString();
                ResultJTCYBG.GFZGSCSQBH = input.TrailingData.Id;
                ResultJTCYBG.GFZGSCSQJTCYBH = GFZGSCSQBH;  //家庭成员信息表的主键id赋值给变更表的GFZGSCSQJTCYBH  
                ResultJTCYBG.BGSJ = System.DateTime.Now;
                await _purFamilyMemberChangesRepository.InsertAsync(ResultJTCYBG);
            }
            return dto;
        }

        private async Task Verify(CreatOrUpdateTrailingUpdate input)
        {
            var Result = await _purqualificationapplyManager.IsExistAsync(input.TrailingData.Id);
            if (Result == false)
            {
                throw new UserFriendlyException("对应信息不存在!");
            }
            //判断第二个子组件传过来的人员证件信息和家庭成员信息不为空
            if (input.TrailingData.purPeoInfors.Count <= 0 || input.purFamilyMemberData.purFamilyInfos.Count <= 0)
            {
                throw new UserFriendlyException("购房人信息不可为空!");
            }
            //判断第二个子组件传过来的人员证件信息和家庭成员中的购房人是否数量相同
            if (input.TrailingData.purPeoInfors.Count > input.purFamilyMemberData.purFamilyInfos.Count)
            {
                throw new UserFriendlyException("购房人基本信息不完善，请补充购房人基本信息!");
            }
            //确保购房申请人联系电话为空(短信验证电话置为空不保存)--待讨论

            //获取人员证件信息中的购房人集合
            string[] BuyPeople = input.TrailingData.purPeoInfors.Select(a => a.GFRXM).ToArray();
            //获取家庭成员信息中的人员姓名集合
            string[] FamilyPeople = input.purFamilyMemberData.purFamilyInfos.Select(b => b.XM).ToArray();

            //判断第二个子组件传过来的人员证件信息和家庭成员中的购房人姓名是否相同
            for (int i = 0; i < BuyPeople.Length; i++)
            {
                bool exist = ((IList)FamilyPeople).Contains(BuyPeople[i].ToString());

                if (exist == false)
                {
                    throw new UserFriendlyException("购房人信息不正确，请核实!");
                }
            }

            //检查证件号码是否重复
            bool isRepeat = input.purFamilyMemberData.purFamilyInfos.GroupBy(i => i.ZJHM).Where(g => g.Count() > 1).Count() > 0;
            if (isRepeat == true)
            {
                throw new UserFriendlyException("证件号码存在重复项，请核查!");
            }

            //验证购房人家庭成员是否在黑名单中
            List<PurFamilyVerifyS> purFamilyVerifies = new List<PurFamilyVerifyS>();
            for (var i = 0; i < input.purFamilyMemberData.purFamilyInfos.Count; i++)
            {
                purFamilyVerifies.Add(new PurFamilyVerifyS() { ZJLX = input.purFamilyMemberData.purFamilyInfos[i].ZJLXDM, ZJHM = input.purFamilyMemberData.purFamilyInfos[i].ZJHM });
            }

            //检验购房人是否在黑名单中
            await _purqualificationapplyManager.Check_JTCYinHMD(purFamilyVerifies);

        }

        /// <summary>
        /// 【PurQualificationApply】第三步--信息上传
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task PurPeoDataUpdate(CreatOrUpdatePurPeoUpdate input)
        {
            //1. 获取当前登录的用户信息（）
            //2. 判断当前登录 是否经济机构用户
            await GetPersonChecker();

            var result = await _purqualificationapplyManager.IsExistAsync(input.purHouseData.Id);
            if (result == false)
            {
                throw new UserFriendlyException("对应信息不存在!");
            }
            var key = input.purHouseData.Id;
            var entity = await _purqualificationapplyRepository.GetAsync(key);

            ObjectMapper.Map(input.purHouseData, entity);
            var ApplyBGResult = await _purqualificationapplyManager.MyUpdateAsync(entity);
            var BGResults = ObjectMapper.Map<PurQualificationChage>(ApplyBGResult);
            BGResults.GFZGSCSQBH = entity.Id;
            BGResults.Id = _purqualificationapplyManager.GetGSChangeSequence();  //需要取序列
            await _purQualificationChageRepository.InsertAsync(BGResults);
        }

        /// <summary>
        /// 【PurQualificationApply】通过id获取购房人详细信息(敏感信息特殊处理)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PurQualificationInfoListDto> GetPurInfoById(EntityDto<string> input)
        {
            //1. 获取当前登录的用户信息（）
            //2. 判断当前登录 是否经济机构用户
            await GetPersonChecker();

            var entity = await _purqualificationapplyRepository.GetAsync(input.Id);

            var dto = ObjectMapper.Map<PurQualificationInfoListDto>(entity);

            //对买受人基本信息判断
            if (string.IsNullOrEmpty(entity.GFRXM) || string.IsNullOrEmpty(entity.ZJHM) || string.IsNullOrEmpty(entity.LXDH))
            {
                throw new UserFriendlyException("用户信息不完善!");
            }
            else
            {
                string[] GFRXMArr = entity.GFRXM.Split(',');
                string[] ZJHMArr = entity.ZJHM.Split(',');
                string[] LXDHArr = entity.LXDH.Split(',');
                List<BuyersInformation> buyersInformations = new List<BuyersInformation>();

                for (int i = 0; i < GFRXMArr.Length; i++)
                {
                    ZJHMArr[i] = ReplaceWithSpecialChar(ZJHMArr[i], 1, 1);
                    LXDHArr[i] = ReplaceWithSpecialChar(LXDHArr[i], 3, 2);
                    buyersInformations.Add(new BuyersInformation() { GFRXM = GFRXMArr[i], ZJHM = ZJHMArr[i], LXDH = LXDHArr[i] });
                }
                dto.buyersInformations = buyersInformations;
                return dto;
            }
        }

        /// <summary>
        ///【PurQualificationApply】根据Id删除信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task DeleteById(EntityDto<string> input)
        {
            var Res = await GetCurrentUserAsync();
            var Result = await _purqualificationapplyManager.FindByIdAsync(input.Id);
            if (Result == null)
            {
                throw new UserFriendlyException("对应信息不存在!");
            }
            //只有申请状态为未申请的数据才可以"删掉"
            if (Result.SQZTDM == "01")
            {
                //软删除：删掉的数据申请状态更为"00"
                Result.SQZTDM = "00";
                Result.SCRBH = Res.UserName;
                Result.SCRXM = Res.Name;
                Result.SCSJ = System.DateTime.Now;
                await _purqualificationapplyManager.UpdateAsync(Result);
            }
            else
            {
                throw new UserFriendlyException("只有状态为未提交的数据可删除!");
            }
        }

        /// <summary>
        /// 提交审核
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SubmitAudit(CreatOrUpdatePurPeoUpdate input)
        {
            //1. 获取当前登录的用户信息（）
            //2. 判断当前登录 是否经济机构用户
            await GetPersonChecker();
            await _purqualificationapplyManager.SubmitAudit(input.purHouseData.Id);
        }

        /// <summary>
        /// 获取分页查询结果
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<PurQualificationApplyListDto>> GetInfosPaged(GetPurQualificationApplysInput input)
        {
            //1. 获取当前登录的用户信息
            //2. 判断当前登录 是否经济机构用户
            await GetPersonChecker();

            var query = _purqualificationapplyRepository.GetAll()
                          .Where(a => a.SJLY.Equals("XMS"))
                          .Where(a => !a.SQZTDM.Equals("00"))
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.GFRXM.Contains(input.FilterText))
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.ZJHM.Contains(input.FilterText))
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.LXDH.Contains(input.FilterText))
                          .WhereIf(!input.SQZTDM.IsNullOrWhiteSpace(), a => a.SQZTDM.Equals(input.SQZTDM))
                          .WhereIf(input.HTDJH == "1", a => !string.IsNullOrEmpty(a.HTDJH))  //已网签
                          .WhereIf(input.HTDJH == "0", a => string.IsNullOrEmpty(a.HTDJH));  //未网签

            // TODO:根据传入的参数添加过滤条件

            var count = await query.CountAsync();

            var entityList = await query
                    .OrderBy(input.Sorting).AsNoTracking()
                    .PageBy(input)
                    .ToListAsync();

            var entityListDtos = ObjectMapper.Map<List<PurQualificationApplyListDto>>(entityList);

            //加密处理
            Encrypt(entityListDtos);

            return new PagedResultDto<PurQualificationApplyListDto>(count, entityListDtos);
        }

        /// <summary>
        /// 对分页查询结果进行加密处理
        /// </summary>
        /// <param name="entityListDtos"></param>
        protected void Encrypt(List<PurQualificationApplyListDto> entityListDtos)
        {
            //新增逻辑处理--返回前的加密处理
            if (entityListDtos.Count > 0)
            {
                foreach (var item in entityListDtos)
                {
                    string ZJHMStr = string.Empty;
                    string LXDHStr = string.Empty;
                    string[] ZJHMArr = item.ZJHM.Split(',');
                    string[] LXDHArr = item.LXDH.Split(',');
                    for (var i = 0; i < ZJHMArr.Length; i++)
                    {

                        ZJHMArr[i] = ReplaceWithSpecialChar(ZJHMArr[i], 1, 1); //证件号码
                        LXDHArr[i] = ReplaceWithSpecialChar(LXDHArr[i], 3, 2); //联系电话

                        ZJHMStr += ZJHMArr[i] + ",";
                        LXDHStr += LXDHArr[i] + ",";
                    }
                    item.ZJHM = ZJHMStr.Substring(0, ZJHMStr.LastIndexOf(","));
                    item.LXDH = LXDHStr.Substring(0, LXDHStr.LastIndexOf(","));
                }
            }
        }

        //证件上传
    }
    #endregion
}
